import datetime
import uuid

from django.core.paginator import Paginator
from rest_framework.response import Response
from rest_framework.views import APIView

from approve.models import Approve, ApprRank, ApprFlow
from dealer.models import Dealer
from order.models import Indent, IndentDetail, IndentHistory
from order.serializer import IndentSerializer, IndentHistorySerializer, IndentDetailSerializer
from stock.models import Goods
from user.models import Staff, Inform
from utils.decorator_ import PermissionCheck


class OrderView(APIView):
    @PermissionCheck('order.view_indent')
    def get(self, request, format=None):
        # 总经理、仓库经理可以查看所有订单，  个人可查看个人订单
        # 查询参数： page 页号, size 每页显示的条目数量
        page = int(request.GET.get('page', '1'))
        size = int(request.GET.get('size', '20'))
        staff = Staff.objects.get(pk=request.user.pk)
        if staff.role.role_id in ['4a1286cefec64c74a39b7fa18a0a6848', '4c2a53b3843e49ebadc4eb56b6f7e86b']:
            data = Indent.objects.all()
        else:
            data = Indent.objects.filter(staff_num=staff.num)
        paginator = Paginator(data, size)
        pager = paginator.page(page)
        # 模型实例化
        indent = IndentSerializer(pager.object_list, many=True)
        return Response({
            'data': indent.data,
            'total': paginator.count,
            'page': pager.number,  # page当前页号
            'pageSize': size,
            'pages': paginator.num_pages  # 总页数
        })

    @PermissionCheck('order.add_indent')
    def post(self, request, format=None):
        goods = request.data.get('goods')
        num = int(request.data.get('num'))
        sign_name = request.data.get('sign_name')
        phone = request.data.get('phone')
        address = request.data.get('address')
        company = request.data.get('company')
        type = request.data.get('type')
        content = request.data.get('content')
        appr_kind = request.data.get('kind')
        approvers_list = request.data.get('approvers')
        ord_id = uuid.uuid4().hex
        if Indent.objects.all():
            ret = str(Indent.objects.count() + 1)
            onum = 'O' + ret.rjust(9, '0')
        else:
            onum = 'O' + '1'.rjust(9, '0')
        goods = Goods.objects.get(pk=goods)
        dealer = Dealer.objects.get(company=company)
        staff = Staff.objects.get(pk=dealer.staff_id)
        appr_id = uuid.uuid4().hex
        if Approve.objects.all():
            ret = str(Approve.objects.count() + 1)
            anum = 'A' + ret.rjust(9, '0')
        else:
            anum = 'A' + '1'.rjust(9, '0')
        if Inform.objects.all():
            ret = str(Inform.objects.count() + 1)
            inum = 'I' + ret.rjust(9, '0')
        else:
            inum = 'I' + '1'.rjust(9, '0')
        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if staff:
            Approve.objects.create(appr_id=appr_id, num=anum, staff_id=staff.staff_id, start_time=start_time,
                                   status="待审批",
                                   content=content, appr_kind=appr_kind)
            for appr in range(len(approvers_list)):
                ApprRank.objects.create(rank_id=uuid.uuid4().hex,
                                        appr_id=appr_id,
                                        rank=appr + 1,
                                        staff_id=approvers_list[appr],
                                        status="待审批")
            ApprFlow.objects.create(flow_id=uuid.uuid4().hex,
                                    appr_id=appr_id,
                                    staff=Staff.objects.get(pk=approvers_list[0]),
                                    status="待审批")
            Inform.objects.create(inform_id=uuid.uuid4().hex,
                                  num=inum,
                                  staff_name=Staff.objects.get(pk=approvers_list[0]).name,
                                  staff_num=Staff.objects.get(pk=approvers_list[0]).num,
                                  time=start_time,
                                  event=content,
                                  status='未读')
        Indent.objects.create(indent_id=ord_id,
                              num=onum,
                              price=goods.retail * num * 0.8,
                              sign_name=sign_name,
                              phone=phone,
                              address=address,
                              type=type,
                              indent_status='待审核',
                              pay_status='未支付',
                              appr_num=anum,
                              create_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                              staff_name=staff.name,
                              staff_num=staff.num,
                              company=company)
        IndentDetail.objects.create(indentdet_id=uuid.uuid4().hex,
                                    indent_id=ord_id,
                                    goods_id=goods.goods_id,
                                    count=num,
                                    price=goods.retail * num * 0.8)
        return Response({'msg': '下单成功,请等待审批结果'})

    @PermissionCheck('order.change_indent')
    def put(self, request, format=None):
        ind_id = request.data.get('indent')
        indent_status = request.data.get('indent_status')
        pay_status = request.data.get('pay_status')
        if IndentHistory.objects.all():
            ret = str(IndentHistory.objects.count() + 1)
            hnum = 'H' + ret.rjust(9, '0')
        else:
            hnum = 'H' + '1'.rjust(9, '0')
        order = Indent.objects.get(pk=ind_id)
        appr = Approve.objects.get(num=order.appr_num)
        order_detail = IndentDetail.objects.get(indent_id=order.indent_id)
        if appr.status == '通过':
            order.indent_status = indent_status
            order.pay_status = pay_status
            order.update_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            order.save()
            indent = IndentSerializer(Indent.objects.get(pk=ind_id), many=False)
            if indent_status == '完成':
                IndentHistory.objects.create(history_id=uuid.uuid4().hex,
                                             num=hnum,
                                             goods_name=Goods.objects.get(pk=order_detail.goods_id).name,
                                             price=order_detail.price,
                                             count=order_detail.count,
                                             total_price=order.price,
                                             address=order.address,
                                             sign_name=order.sign_name,
                                             phone=order.phone,
                                             finish_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                             staff_name=order.staff_name,
                                             company=order.company,
                                             create_time=order.create_time,
                                             indent_status='完成')
            return Response({'data': indent.data})
        elif appr.status == '不通过':
            IndentHistory.objects.create(history_id=uuid.uuid4().hex,
                                         num=hnum,
                                         goods_name=Goods.objects.get(pk=order_detail.goods_id).name,
                                         price=order_detail.price,
                                         count=order_detail.count,
                                         total_price=order.price,
                                         address=order.address,
                                         sign_name=order.sign_name,
                                         phone=order.phone,
                                         finish_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                         staff_name=order.staff_name,
                                         company=order.company,
                                         create_time=order.create_time,
                                         indent_status='未完成')
            return Response({'msg': '审核未通过，请查看原因后重新申请'})
        else:
            return Response({'msg': '订单不存在'})


class OrderHisView(APIView):
    @PermissionCheck('order.view_indenthistory')
    def get(self, request, format=None):
        # 总经理、仓库经理可以查看所有订单，  个人可查看个人订单
        staff = Staff.objects.get(pk=request.user.pk)
        if staff.role.role_id in ['4a1286cefec64c74a39b7fa18a0a6848', '4c2a53b3843e49ebadc4eb56b6f7e86b']:
            order = IndentHistorySerializer(IndentHistory.objects.all(), many=True)
        else:
            order = IndentHistorySerializer(IndentHistory.objects.filter(staff_num=staff.num), many=True)
        return Response({'data': order.data})

class OrderDetailView(APIView):
    @PermissionCheck('order.view_indentdetail')
    def get(self, request, pk, format=None):
        indentdet = IndentDetailSerializer(IndentDetail.objects.get(pk=pk),many=False)
        return Response({'data':indentdet.data})
